const shelljs = require('shelljs')
const path = require('path')
const fs = require('fs')
const os = require('os')

// rollup 打包，copy readme 和 package.json
shelljs.exec('rollup -c')
shelljs.exec(`${os.type() === 'Windows_NT' ? 'copy' : 'cp'} package.json README.md dist`)

// 删除 package.json 多余字符
const packageJsonPath = path.resolve(__dirname, '../dist/package.json')
let fileText = fs
  .readFileSync(packageJsonPath, 'utf8')
  ?.replace(/dist\//gi, '')
  ?.replace(/"scripts"[\s\S]*?},?/gi, '')
  ?.replace(/"dependencies"[\s\S]*?},?/gi, '')
  ?.replace(/"devDependencies"[\s\S]*?},?/gi, '')
fs.writeFileSync(packageJsonPath, fileText, 'utf8')
shelljs.exec(`npx prettier --write ${packageJsonPath}`)

// 判断是否需要发布
const commandArguments = process.argv.splice(2)
if (commandArguments.includes('--publish')) {
  shelljs.cd('dist')
  shelljs.exec('npm publish --registry https://registry.npmjs.org --access=public')
}
